<template>
	<view class="canvas-container"
		:style="{ width: canvasSize + 'px', height: canvasSize + 'px',fontSize:canvasSize/2+'px' }">
		<view class="avatar-text">
			{{fallbackText[0]}}
		</view>
		<!-- <canvas :canvas-id="'avatarGrid-' + rand"
			:style="{ width: canvasSize + 'px', height: canvasSize + 'px' }"></canvas> -->
	</view>
</template>

<script>
	export default {
		name: 'avatar-grid',
		props: {
			imgs: {
				type: Array,
				default: () => [],
				validator(value) {
					return value.length >= 0 && value.length <= 9;
				}
			},
			fallbackText: {
				type: String,
				default: ''
			},
			canvasSize: {
				type: Number,
				default: 50
			},
			expires: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				rand: Date.now(),
				ctx: null,
				cellSize: 0
			};
		},
		mounted() {
			this.$emit("draw")
			/* this.ctx = uni.createCanvasContext('avatarGrid-' + this.rand, this);
			this.updateCellSize();
			this.drawGrid();
			if (this.expires > 0) {
				const self = this
				setTimeout(() => {
					// console.log("超时");
					self.$emit("draw")
				}, this.expires)
			} */
		},
		methods: {
			updateCellSize() {
				const {
					imgs,
					canvasSize
				} = this;
				const numImgs = imgs.length;

				if (numImgs === 0) {
					this.cellSize = canvasSize;
				} else if (numImgs === 1) {
					this.cellSize = canvasSize / 2;
				} else if (numImgs <= 2) {
					this.cellSize = (canvasSize - 1) / 2;
				} else if (numImgs <= 6) {
					this.cellSize = (canvasSize - 2) / 3;
				} else {
					// For 7 to 9 images, we'll just use the default 3x3 grid
					this.cellSize = (canvasSize - 2) / 3;
				}
			},
			drawFallbackText() {
				const {
					canvasSize,
					fallbackText
				} = this;
				const fontSize = canvasSize / 2;
				this.ctx.setFontSize(fontSize);
				this.ctx.setTextAlign('center');
				this.ctx.setFillStyle('#ffffff');

				// Calculate the baseline offset to center the text vertically
				const baselineOffset = fontSize * 0.35; // Approximation for most fonts

				// Draw the background with rounded corners
				this.ctx.save();
				this.ctx.beginPath();
				this.ctx.arc(canvasSize / 2, canvasSize / 2, canvasSize / 2 - 8, 0, Math.PI * 2);
				this.ctx.clip();
				this.ctx.setFillStyle('#007FFF');
				this.ctx.fillRect(0, 0, canvasSize, canvasSize);
				this.ctx.restore();

				// Draw the text
				this.ctx.fillText(fallbackText.charAt(0).toUpperCase(), canvasSize / 2, canvasSize / 2 + baselineOffset);
				this.ctx.draw(false, () => {
					this.$emit('drawn');
				});
			},

			drawGrid() {
				if (!this.ctx) {
					return;
				}
				const {
					imgs,
					cellSize,
					canvasSize
				} = this;
				const numImgs = imgs.length;
				this.ctx.clearRect(0, 0, canvasSize, canvasSize);
				if (numImgs === 0 && this.fallbackText) {
					this.drawFallbackText();
				} else {
					let loadedCount = 0;
					const drawImage = (img, x, y, cellSize) => {
						uni.getImageInfo({
							src: img,
							success: (res) => {
								this.ctx.drawImage(res.path, x, y, cellSize, cellSize);
								loadedCount++;
								if (loadedCount === numImgs) {
									this.ctx.draw(false, () => {
										this.$emit('drawn');
									});
								}
							},
							fail: () => {
								console.log("绘制头像失败")
								loadedCount++;
								if (loadedCount === numImgs) {
									this.ctx.draw(false, () => {
										this.$emit('drawn');
									});
								}
							}
						});
					};

					if (numImgs === 1) {
						const x = (canvasSize - cellSize) / 2;
						const y = (canvasSize - cellSize) / 2;
						drawImage(imgs[0], x, y, cellSize);
					} else if (numImgs <= 2) {
						imgs.forEach((img, index) => {
							const x = index * (cellSize + 1);
							const y = (canvasSize - cellSize) / 2;
							drawImage(img, x, y, cellSize);
						});
					} else if (numImgs <= 6) {
						imgs.forEach((img, index) => {
							const row = Math.floor(index / 3);
							const col = index % 3;
							const x = col * (cellSize + 1);
							const y = row * (cellSize + 1) + (canvasSize - 3 * cellSize - 2) / 2;
							drawImage(img, x, y, cellSize);
						});
					} else {
						// For 7 to 9 images, we'll just use the default 3x3 grid
						imgs.forEach((img, index) => {
							const row = Math.floor(index / 3);
							const col = index % 3;
							const x = col * (cellSize + 1);
							const y = row * (cellSize + 1) + (canvasSize - 3 * cellSize - 2) / 2;
							drawImage(img, x, y, cellSize);
						});
					}
				}
			}
		},
		watch: {
			imgs: {
				handler() {
					this.updateCellSize();
					this.drawGrid();
				},
				deep: true
			},
			canvasSize: {
				handler() {
					this.updateCellSize();
					this.drawGrid();
				},
				immediate: true
			},
			fallbackText: {
				handler() {
					this.drawGrid();
				},
				immediate: true
			}
		}
	};
</script>

<style scoped>
	.canvas-container {
		display: flex;
		justify-content: center;
		align-items: center;
		color: #ffffff;
		/* background-color: #eef0f3; */
		background-color: #007FFF;
		/* background: linear-gradient(135deg,
				#E6F7F7 0%,
				#EBF4F8 25%,
				#F0F1FF 50%,
				#F7F8FF 75%,
				#FFFFFF 100%); */
		border-radius: 8px;
		overflow: hidden;
	}
</style>